package com.servlet;

import com.bean.Book;
import com.dao.BooksUtilsDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;


@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        @SuppressWarnings("unchecked")
		ArrayList<Book> cart = (ArrayList<Book>) session.getAttribute("cart");
        if (cart == null){
            cart = new ArrayList<Book>();
            session.setAttribute("cart", cart);
        }
        BooksUtilsDao dao = new BooksUtilsDao();
        try {
            String[] checkboxes = request.getParameterValues("checkbox");
            for(String id: checkboxes ){
                dao.add(id);
                dao.totalprice(id);
                ArrayList<Book> book = (ArrayList<Book>) dao.findId(id);
                cart.add(book.get(0));

            }
        }catch (Exception e){
            response.sendRedirect("BookListServlet");
            return;

        }
        response.sendRedirect("CartServlet");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
